<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="用户角色">
          <el-select v-model="formInline.userrole" placeholder="用户角色" clearable>
            <el-option
              v-for="item in userroles"
              :key="item.strRolenum"
              :label="item.strRolename"
              :value="item.strRolenum"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="用户机构">
          <el-cascader
            v-model="formInline.iOrgsysnum"
            :show-all-levels="false"
            clearable
            :options="options"
            :props="{ multiple: true, emitPath:false,checkStrictly: true,expandTrigger: 'hover',value:'strOrgnum',label:'strOrgname',children: 'yhlist' }"
          />
        </el-form-item>
        <el-form-item label="用户手机号">
          <el-input v-model="formInline.strPhone" placeholder="用户手机号" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
          <el-button type="primary" icon="el-icon-edit" @click="openForm()">添加</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-dialog title="新增用户" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="90px"
        :inline="true"
        :label-position="lablePosition"
      >
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="用户账号" prop="strUsernum">
              <el-input v-model="form.strUsernum" placeholder="用户账号" class="inptw200" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户姓名" prop="strUsername">
              <el-input v-model="form.strUsername" placeholder="用户姓名" class="inptw200" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户密码" prop="strPassword">
              <el-input v-model="form.strPassword" placeholder="用户密码" class="inptw200" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="手机号码" prop="strPhone">
              <el-input v-model="form.strPhone" placeholder="手机号码" maxlength="11" class="inptw200" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属机构" prop="iOrgsysnum">
              <el-cascader
                v-model="form.iOrgsysnum"
                :show-all-levels="false"
                :options="options"
                :props="{ multiple: true, emitPath:false,checkStrictly: true,expandTrigger: 'hover',value:'strOrgnum',label:'strOrgname',children: 'yhlist' }"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="柜员号" prop="strVipNum">
              <el-input v-model="form.strVipNum" placeholder="柜员号" class="inptw200" />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item prop="strRole" label="选择角色">
              <el-select v-model="form.strRole" placeholder="请选择角色" multiple clearable>
                <el-option
                  v-for="role in roles"
                  :key="role.iRolesysnum"
                  :value=" role.iRolesysnum"
                  :label="role.strRolename"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <div v-for="ietm in roleMenu" :key=" ietm.productType" style="margin: 15px 0;">
          {{ ietm.productType }}
          <div>
            <span
              v-for="menu in ietm.productNamelist"
              :key=" menu.productName"
            >{{ menu.productName }}</span>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="success('form')">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="修改用户" :visible.sync="dialogFormUpdate">
      <el-form ref="updateform" :rules="updaterules" :model="updateform" label-width="100">
        <el-row :gutter="40">
          <el-col :span="8">
            <el-form-item label="用户账号" prop="strUsernum">
              <el-input v-model="updateform.strUsernum" placeholder="用户账号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="用户姓名" prop="strUsername">
              <el-input v-model="updateform.strUsername" placeholder="用户姓名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="40">
          <el-col :span="8">
            <el-form-item label="手机号码" prop="strPhone">
              <el-input v-model="updateform.strPhone" placeholder="手机号码" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所属机构" prop="iOrgsysnum">
              <el-cascader
                v-model="updateform.iOrgsysnum"
                :show-all-levels="false"
                :options="options"
                :props="{ multiple: true, emitPath:false,checkStrictly: true,expandTrigger: 'hover',value:'strOrgnum',label:'strOrgname',children: 'yhlist' }"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="柜员号" prop="strVipNum">
              <el-input v-model="updateform.strVipNum" placeholder="柜员号" />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="选择角色" prop="updatestrRole">
              <el-select v-model="updateform.updatestrRole" placeholder="请选择角色" multiple clearable>
                <el-option
                  v-for="role in roles"
                  :key="role.iRolesysnum"
                  :label="role.strRolename"
                  :value=" role.iRolesysnum"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <div v-for="ietm in roleMenu" :key="ietm.strMenu" style="margin: 15px 0;">
          {{ ietm.strMenu }}
          <div>
            <span v-for="menu in ietm.icon" :key="menu.icon">{{ menu.icon }}</span>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormUpdate = false">取 消</el-button>
        <el-button type="primary" @click="updatesucc('updateform')">确 定</el-button>
      </div>
    </el-dialog>

    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="id" label="序号" width="60" />
      <el-table-column prop="strUsernum" label="用户编号" />
      <el-table-column prop="strRolename" label="角色名称" />
      <el-table-column prop="strPhone" label="用户手机号" />
      <el-table-column prop="strUsername" label="用户姓名" />
      <el-table-column prop="strVipNum" label="柜员号" />
      <el-table-column prop="strOrgName" label="所属机构" />
      <el-table-column label="操作" width="180">
        <template slot-scope="{row}">
          <template v-if="iOrgsysnum === -1||row.iOrgsysnum === iOrgsysnum">
            <el-button type="primary" size="mini" @click="handleDialogVisible(row)">修改</el-button>
            <el-button type="danger" size="mini" @click="DeleteUser(row)">删除</el-button>
          </template>
          <template v-else>
            <span>无权限</span>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <Pagination
      v-show="total>0"
      :total="total"
      :page.sync="pagenum"
      :limit.sync="limit"
      :layout="layout"
      @pagination="getUserList"
    />
  </div>
</template>
<script>
import { getOrglists } from '../../api/addTag'
import {
  selectAppUserInfo,
  delUserInfo,
  queryRoleByTerminal,
  addUserInfo,
  getProductTypeAndName,
  listUserRole,
  updUserInfo,
  showRoleAuth
} from '@/api/system/system'
import Pagination from '@/components/Pagination'
import {
  validatePhone,
  validatestrUsernum,
  validatename,
  validatepwd
} from '../../utils/validateForm'
import { mapGetters } from 'vuex'

export default {
  components: {
    Pagination
  },
  data() {
    return {
      formInline: {
        userrole: '',
        iOrgsysnum: '',
        strPhone: ''
      },
      lablePosition: 'right',
      form: {
        strUsernum: '',
        strUsername: '',
        strPassword: '',
        strPhone: '',
        iOrgsysnum: '',
        strVipNum: '',
        strRole: []
      },
      rules: {
        strUsernum: [
          { required: true, validator: validatestrUsernum, trigger: 'blur' }
        ],
        strUsername: [
          { required: true, validator: validatename, trigger: 'blur' }
        ],
        iOrgsysnum: [
          { required: true, message: '请选择所属机构', trigger: 'change' }
        ],
        strPassword: [
          { required: true, validator: validatepwd, trigger: 'blur' }
        ],
        strPhone: [
          {
            required: true,
            validator: validatePhone,
            trigger: 'blur'
          }
        ],
        strRole: [
          {
            required: true,
            message: '请选择角色权限',
            trigger: 'change'
          }
        ]
      },
      updaterules: {
        strUsernum: [
          { required: true, validator: validatestrUsernum, trigger: 'blur' }
        ],
        strUsername: [
          { required: true, validator: validatename, trigger: 'blur' }
        ],
        iOrgsysnum: [
          { required: true, message: '请选择所属机构', trigger: 'change' }
        ],
        strPassword: [
          { required: true, validator: validatepwd, trigger: 'blur' }
        ],
        strPhone: [
          {
            required: true,
            message: '请输入手机号',
            trigger: 'blur'
          },
          { max: 30, message: '长度最多30个字符', trigger: 'blur' }
        ],
        updatestrRole: [
          {
            required: true,
            message: '请选择角色权限',
            trigger: 'change'
          }
        ]
      },
      updateform: {
        strUsernum: '',
        strUsername: '',
        strPassword: '',
        strPhone: '',
        iOrgsysnum: '',
        updatestrRole: [],
        strVipNum: ''
      },
      tableData: [],
      dialogFormVisible: false,
      dialogFormUpdate: false,
      options: [],
      userroles: [],
      roles: [],
      strRole: [],
      roleMenu: [],
      strRoles: [],
      icon: [],
      total: 0,
      limit: 5,
      pagenum: 1,
      currentpage: 1,
      layout: 'total, prev, pager, next, jumper'
    }
  },
  computed: {
    ...mapGetters(['iOrgsysnum'])
  },
  created() {
    this.getUserList()
    queryRoleByTerminal({ iType: 1 }).then(res => {
      this.userroles = res.data
      this.roles = res.data
    })
  },
  methods: {
    onSubmit() {
      var userrole = this.formInline.userrole
      var phone = this.formInline.strPhone
      if (!(this.formInline.iOrgsysnum instanceof Array)) {
        let iOrgsysnum = []
        iOrgsysnum.push(this.formInline.iOrgsysnum)
        iOrgsysnum = iOrgsysnum.splice(-1)
        this.formInline.iOrgsysnum = iOrgsysnum[0]
      } else {
        let iOrgsysnum = this.formInline.iOrgsysnum
        iOrgsysnum = iOrgsysnum.splice(-1)
        this.formInline.iOrgsysnum = iOrgsysnum[0]
      }
      selectAppUserInfo({
        rows: this.pagenum,
        iUsertype: 1,
        strRoleNum: userrole,
        strPhone: phone,
        iOrgsysnum: this.formInline.iOrgsysnum
      }).then(res => {
        this.tableData = res && res.data
        this.total = res && res.total
      })
    },
    getUserList() {
      selectAppUserInfo({
        rows: this.pagenum,
        iUsertype: 1,
        iOrgsysnum: this.$store.getters.iOrgsysnum
      }).then(res => {
        this.tableData = res && res.data
        this.total = !res ? 0 : res.total
      })
      getOrglists({ iOrgnum: this.$store.getters.iOrgsysnum }).then(res => {
        if (this.$store.getters.iOrgsysnum === -1) {
          this.options = res && res.data
        } else {
          this.options.push(res && res.data)
        }
      })
    },
    openForm() {
      this.form.strUsernum = ''
      this.form.strUsername = ''
      this.form.strPassword = ''
      this.form.strPhone = ''
      this.form.iOrgsysnum = []
      this.dialogFormVisible = true
    },
    getroleqx() {
      getProductTypeAndName({ iRolesysnum: JSON.stringify(this.strRole) }).then(
        res => {
          this.roleMenu = res.productList
        }
      )
    },
    handleDialogVisible(row) {
      this.dialogFormUpdate = true
      this.updateUser(row)
    },
    updateUser(row) {
      this.updateform.updatestrRole = []
      this.updateform.iOrgsysnum = []
      this.updateform.id = row.id
      this.updateform.strUsernum = row.strUsernum
      this.updateform.strUsername = row.strUsername
      this.updateform.strPassword = row.strPassword
      this.updateform.strPhone = row.strPhone
      this.updateform.iOrgsysnum = row.iOrgsysnum + ''
      this.updateform.iUsersysnum = row.iUsersysnum
      this.updateform.strVipNum = row.strVipNum
      this.updateform.iRolesysnum = row.iRolesysnum
      listUserRole({ iUsersysnum: row.iUsersysnum }).then(res => {
        var resu = res.data.toString()
        if (resu.indexOf(',') > 0) {
          const arr = resu.split(',').map(j => {
            return parseInt(j)
          })
          this.updateform.updatestrRole = arr
        } else {
          this.updateform.updatestrRole.push(parseInt(resu))
        }
        // this.dialogFormUpdate = false
      })
      // showRoleAuth({iRolesysnum: this.updatestrRole}).then((res) => {
      //     this.roleMenu = res.data;
      // })
    },
    getroleup() {
      showRoleAuth({ iRolesysnum: JSON.stringify(this.updatestrRole) }).then(
        res => {
          this.roleMenu = res.data
        }
      )
    },
    updatesucc(formName) {
      if (!(this.updateform.iOrgsysnum instanceof Array)) {
        let iOrgsysnum = []
        iOrgsysnum.push(this.updateform.iOrgsysnum)
        iOrgsysnum = iOrgsysnum.splice(-1)
        this.updateform.iOrgsysnum = iOrgsysnum[0]
      } else {
        let iOrgsysnum = this.updateform.iOrgsysnum
        iOrgsysnum = iOrgsysnum.splice(-1)
        this.updateform.iOrgsysnum = iOrgsysnum[0]
      }
      this.updateform.iUsertype = 1
      this.updateform.strRole = this.updateform.updatestrRole
      this.$refs[formName].validate(valid => {
        if (valid) {
          updUserInfo(this.updateform).then(res => {
            this.$message({
              type: 'success',
              message: '修改成功!'
            })
            this.dialogFormUpdate = false
            this.$refs[formName].resetFields()
            this.getUserList()
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    success(formName) {
      if (!(this.form.iOrgsysnum instanceof Array)) {
        let iOrgsysnum = []
        iOrgsysnum.push(this.form.iOrgsysnum)
        iOrgsysnum = iOrgsysnum.splice(-1)
        this.form.iOrgsysnum = iOrgsysnum[0]
      } else {
        let iOrgsysnum = this.form.iOrgsysnum
        iOrgsysnum = iOrgsysnum.splice(-1)
        this.form.iOrgsysnum = iOrgsysnum[0]
      }
      this.form.iUsertype = 1
      this.form.strRoleNum = this.form.strRole
      delete this.form.strRolename
      this.$refs[formName].validate(valid => {
        if (valid) {
          addUserInfo(this.form).then(res => {
            this.$message({
              type: 'success',
              message: '新增成功!'
            })
            this.dialogFormVisible = false
            this.$refs[formName].resetFields()
            this.getUserList()
            // } else if (res.result === -2) {
            //   this.$message({
            //     type: 'error',
            //     message: '用户账号已存在!'
            //   })
            // } else {
            //   this.$message({
            //     type: 'error',
            //     message: '新增失败!'
            //   })
            // }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    DeleteUser(row) {
      var strUsername = row.strUsername
      this.$confirm(
        '此操作将永久用户名称为：' + strUsername + ', 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          delUserInfo({ id: row.id }).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getUserList()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    changInpt(val) {
      console.log(val)
    }
  }
}
</script>
